package com.frank.code_notes.C01_array;


import cn.hutool.core.lang.Console;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description 54.螺旋矩阵
 * @Author zhoujr
 * @Data 2024/11/28 21:23
 */
public class L054SpiralMatrix {

    /**
     * @Description 确定四个边界，边界向内收缩，收缩后大于对应边结束。
     */
    public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> resList = new ArrayList<>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return resList;
        }
        int l = 0, t = 0, r = matrix[0].length - 1, b = matrix.length - 1;
        resList = new ArrayList<>((r + 1) * (b + 1));
        while (true) {
            // 下一圈起点
            for (int i = l; i <= r; i++) resList.add(matrix[t][i]);
            if (++t > b) break;
            for (int i = t; i <= b; i++) resList.add(matrix[i][r]);
            if (l > --r) break;
            for (int i = r; i >= l ; i--) resList.add(matrix[b][i]);
            if (t > --b) break;
            for (int i = b; i >= t; i--) resList.add(matrix[i][l]);
            if (++l > r) break;
        }
        return resList;
    }

    public static void main(String[] args) {
        Console.log(spiralOrder(new int[][]{
                {2, 3, 4},
                {5, 6, 7},
                {8, 9, 10},
                {11,12,13},
                {14,15,16}
        }));
    }

}
